package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.IEmployeeService;
import org.apache.commons.lang.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    /**
     * 用于完成用户登录的方法
     * @param session
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R login(HttpSession session,@RequestBody Employee employee){
        if (employee == null
            || StringUtils.isEmpty(employee.getUsername())
            || StringUtils.isEmpty(employee.getPassword())){
            return R.error("用户名或密码不能为空");
        }
        //查询数据库 select * from employee where username=?
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername,employee.getUsername());
        Employee existEmp = employeeService.getOne(qw);
        if (existEmp == null){
            return R.error("账号不存在!");
        }
        if (existEmp.getStatus() == 0){
            return R.error("账户已经禁用!");
        }
        String password = existEmp.getPassword(); //数据库密文
        String password1 = employee.getPassword();//明文
        password1 = DigestUtils.md5DigestAsHex(password1.getBytes());
        if (password.equals(password1)){
            //登录成功，返回code:1 和 data: 用户信息
            // 将用户数据存入会话中【session】 如何获取session!
            existEmp.setPassword(null);
            session.setAttribute("loginUser",existEmp);
            return R.success(existEmp);
        }
        //登录失败，返回code:0 和 msg 用户名或密码错误
        return R.error("用户名或密码错误!");
    }
    /**
     * 用户退出
     * @param httpSession
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpSession httpSession){
        httpSession.removeAttribute("loginUser");
        return R.success(null);
    }
    /**
     * 添加成员
     * @param session
     * @param employee
     * @return
     */
    @PostMapping
    public R save(HttpSession session,@RequestBody Employee employee){
        //0、检查数据，哪些是需要处理的
        //0.1: 密码使用默认的123456 ， 需要加密 DigestUtils.md5DigestAsHex
        String password= DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        //0.2： status 不需要处理，数据库默认是1
        //0.3： create_time 和 update_time ,设置为当前系统时间  LocalDateTime.now()
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        //0.4： create_user 和 update_user 创建人和修改人，应该是当前登陆人，从session中获取
//        Employee loginUser = (Employee) session.getAttribute("loginUser");
//        employee.setUpdateUser(loginUser.getId());
//        employee.setCreateUser(loginUser.getId());
        //1、调用业务层保存 employee数据
        boolean save = employeeService.save(employee);
        //2、返回结果R
        if (save){
            return R.success(null);
        }else {
            return R.error("保存失败!");
        }
    }
    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R pageQuery(Integer page,Integer pageSize,String name){
        IPage<Employee> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        //封装查询条件
        if (StringUtils.isNotEmpty(name)){
            qw.like(Employee::getName,name);
        }
        // 进行带条件的分页查询， employeeService.page(pageInfo,qw);
        employeeService.page(pageInfo, qw);
        // 通过pageInfo对象获取分页结果
        // 1、List<> 集合 records  2、总记录数 total
        List<Employee> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        Map data = new HashMap();
        data.put("records",records);
        data.put("total",total);
        return R.success(data);
    }
    /**
     * 修改数据
     * @param session
     * @param employee
     * @return
     */
    @PutMapping
    public R update(HttpSession session,@RequestBody Employee employee){
        //1、修改员工数据 update_time
        employee.setUpdateTime(LocalDateTime.now());
        //2、修改员工数据 update_user 从sesion中获取员工id
        Employee loginUser = (Employee) session.getAttribute("loginUser");
        employee.setUpdateUser(loginUser.getId());
        //3、调用业务层修改员工信息 updateById()
        employeeService.updateById(employee);
        return R.success("修改成功");
    }
    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getId(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        if (employee != null){
            return R.success(employee);
        }
        return R.error("查询失败");
    }
}
